﻿#include "widget_gpio_output.h"
#include "arrow_item.h"
#include "ui_widget_gpio_output.h"

#include <QButtonGroup>
#include <QCheckBox>
#include <QGraphicsProxyWidget>
#include <QHBoxLayout>
#include <com_manager.h>

Widget_GPIO_Output::Widget_GPIO_Output(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget_GPIO_Output)
{
    ui->setupUi(this);

    ui->label_gpio->hide();
    ui->pushButton_read->hide();


    scene = new QGraphicsScene();
    view = new QGraphicsView(scene);

    QHBoxLayout *layout = new QHBoxLayout;
    //dw new5
    // view = new QGraphicsView(scene);

    view->centerOn(0, 0);

    //view = new MyFasterGraphicView(scene);
    view->setViewportUpdateMode(QGraphicsView::SmartViewportUpdate);

    layout->addWidget(view);
    layout->setMargin(0);
    //QWidget *widget = new QWidget;
    ui->widget-> setLayout(layout);

    // this->setCentralWidget(view);
    scene->setSceneRect(0,0,ui->widget->width(),ui->widget->height());
    //  scene->setRect(view->rect());
    view->setAlignment(Qt::AlignLeft | Qt::AlignTop);
    view->setRenderHint(QPainter::Antialiasing);
    // pen = new QPen();
    // scene->setPen(pen);
    // brush = new QBrush(*(new QColor("white")),Qt::NoBrush);
    // scene->setBrush(brush);

    if ( GpioSetting::gpio.count() > 0)
    {
            if (com_manager::instance()->comList.count()>0)
                initChart( com_manager::instance()->comList[0], 0 );
    }
}

Widget_GPIO_Output::~Widget_GPIO_Output()
{
    delete ui;
}

void Widget_GPIO_Output::initChart(QString com, int index)
{
    com_name = com;
    gpio_id = index;

    GPIO* gpio = GpioSetting::gpio[com_name][index];
    if(gpio!=NULL )
        _gpio = *gpio;
    _gpio.mode_input = 0;

    ui->label_gpio->setText("寄存器值："+gpio->toString());
    ui->label_new_gpio->setText(_gpio.toString());

    scene->clear();

    QPen pen_enable (Qt::black , 3, Qt::SolidLine);
    QPen pen_disable(Qt::gray, 2, Qt::DashLine);

    QPen pen_pin(pen_enable);
    QPen pen_user(pen_disable);
    if ( !_gpio.on)
    {
        pen_pin = QPen(pen_disable);
        pen_user  = QPen(pen_enable);
    }

    ////////////////////////////////////////////////////////////
    ///远程节点
      scene->addRect (QRect(440-10, 10, 240, 116 ));

      remote_id = new QLineEdit("");
    QGraphicsProxyWidget * pID=scene->addWidget(remote_id);
    pID->setPos(440,60);
    pID->setGeometry(QRect(440,50, 80, 32));

    QRegExp rx_id("^(254|1[0-9][0-9]|2[0-4][0-9]|25[0-4])$");
    QRegExpValidator  *v_id =new QRegExpValidator (rx_id);
    remote_id->setValidator(v_id);
    remote_id->setText(QString::number(_gpio.remote_id));

    remote_bit = new QLineEdit("");
    QGraphicsProxyWidget * pBIT=scene->addWidget(remote_bit);
    pBIT->setPos(440,90 );
    pBIT->setGeometry(QRect(440,88, 80, 32));
    QRegExp rx_bit("^([0-9]|1[0-5])$");
    QRegExpValidator  *v_bit =new QRegExpValidator (rx_bit);
    remote_bit->setValidator(v_bit);

    remote_bit->setText(QString::number(_gpio.remote_bit));

    QGraphicsProxyWidget * label_ =scene->addWidget(new QLabel("远程节点"));
    label_->setPos(440,160-60-40-40);
    QGraphicsProxyWidget * label_id=scene->addWidget(new QLabel("ID(1~254)"));
    label_id->setPos(524,60 );
    QGraphicsProxyWidget *  label_bit=scene->addWidget(new QLabel("BIT位索引(0~15)"));
    label_bit->setPos(524,90 );

    arrow_0 = new ArrowItem(QPoint(430,70), QPoint(380,70));
    scene->addItem(arrow_0);
    arrow_0->setPen(pen_pin);

    remote_id->setEnabled(_gpio.on);
    remote_bit->setEnabled(_gpio.on);
    connect(remote_id, &QLineEdit::textChanged, [=](QString text) {
        bool ok;
        int id =  text .toInt(&ok);
        if (ok){ _gpio.remote_id = id; updateChart();}
     });
     connect(remote_bit, &QLineEdit::textChanged, [=] (QString text){
         bool ok;
         int bit =  text .toInt(&ok);
         if (ok){ _gpio.remote_bit = bit; updateChart();}
     });
         ////////////////////////////////////////////////////////////

      btnBus = new QPushButton("BUS") ;
btnBus->setCheckable(true);
    //scene->setPen(pen);
 //   scene->addRect ();
    QGraphicsProxyWidget * bus=scene->addWidget(btnBus) ;
    btnBus->setGeometry(QRect(120, 100-60, 260, 60 ));
  //  bus->setPos( QPoint(230, 120-60));

    btnBus->setChecked(_gpio.on);
    connect(btnBus, &QPushButton::clicked, [=] {
        _gpio.on =1;
        updateChart();});
    //  scene->add_Line(200,160, 200, 260);

    //brush->setColor(Qt::green);
    // scene->setPen(pen);

    QPolygon polygon;
   // polygon.append(QPoint(250,160-60) );
    polygon.append(QPoint(250,200-60) );
    polygon.append(QPoint(160,200-60) );
    polygon.append(QPoint(160,260-60) );

    QPainterPath path  ;
    path.addPolygon(polygon);
    item_path= scene->addPath(path, pen_pin) ;
    item_path->setPen(pen_pin);


    arrow_1 = new ArrowItem(QPoint(250,160-60), QPoint(250,200-60));
    scene->addItem(arrow_1);
    arrow_1->setPen(pen_pin);

    btnFlip = new QCheckBox("翻转") ;    
    btnFlip->setStyleSheet(" QCheckBox{border: 1px solid #b1b1b1; }");
    btnFlip->setEnabled(_gpio.on);
    QGraphicsProxyWidget * pFlipWidget=scene->addWidget(btnFlip);
    // pFlipWidget->setPos(120,260);
    pFlipWidget->setGeometry(QRect(120,240-60, 80, 40));
    pFlipWidget->setFlags(QGraphicsItem::ItemIsFocusable | QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemIsMovable); //通过QGraphicsProxyWidget指针设置其可选、可移动、可聚焦

    connect(btnFlip, &QPushButton::clicked, [=] {
        // mHelper::ShowMessageBoxInfoX("翻转");

        _gpio.flip = btnFlip->isChecked();
        updateChart();
    });

    line_1=  scene->addLine(160,280-60, 160, 360-60);
    line_1->setPen(pen_pin);

    arrow_2 = new ArrowItem(QPoint(160,300-60+20), QPoint(160, 360-60+20));
    scene->addItem(arrow_2);
    arrow_2->setPen(pen_enable); //!!

    labelPin = new QLabel("引脚") ;
labelPin->setAlignment(Qt::AlignHCenter|Qt::AlignCenter);
labelPin->setFrameShape( QFrame::Box );

    QGraphicsProxyWidget * pWidgetPin=scene->addWidget(labelPin);
    pWidgetPin->setPos(160,360-60+20);
    pWidgetPin->setGeometry(QRect(120,360-60+20, 80, 40));
    pWidgetPin->setFlags(QGraphicsItem::ItemIsFocusable | QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemIsMovable); //通过QGraphicsProxyWidget指针设置其可选、可移动、可聚焦

  //  btnPin->setChecked(_gpio.on);
//    connect(btnPin, &QPushButton::clicked, [=] {
//        _gpio.on =1;
//        updateChart();});

    QLabel * label_pin = new QLabel(QString("GPIO pin: %1").arg(gpio_id));
    QGraphicsProxyWidget * plabel_pin=scene->addWidget(label_pin);
    plabel_pin->setPos(120,360-60+40 +20);

    //////////////////////////////////////
//    QPolygon polygon_;
//    //polygon_.append(QPoint(250,160) );
//    polygon_.append(QPoint(160,300-60) );
//    polygon_.append(QPoint(540,300-60) );

//    path .clear() ;
//    path.addPolygon(polygon_);

  //  user_path=  scene->addPath(path, pen_user) ;
  //  user_path->setPen(pen_user);

    arrow_3 = new ArrowItem(QPoint(340-80,300-60+20), QPoint(160, 300-60+20));
    scene->addItem(arrow_3 );
    arrow_3->setPen(pen_user);
     //  scene->add_Line(140,360, 340, 360);

    //默认值
    QLabel * label = new QLabel("默认值");
    QGraphicsProxyWidget * plabel=scene->addWidget(label);
    plabel->setPos(300-40,260-80  +4+20);

    user_default = new QComboBox;
    user_default->addItem("0");
    user_default->addItem("1");
    QGraphicsProxyWidget * pCombo=scene->addWidget(user_default);
    pCombo->setPos(300,260-60);
    pCombo->setGeometry(QRect(300-40,260-60+26+20, 80, 32));
    connect(user_default, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged), [=](int index){
        _gpio.level = index;
        updateChart();
    });
    arrow_4 = new ArrowItem(QPoint(400,300-60+20), QPoint(380-40,300-60+20));
    scene->addItem(arrow_4 );
    arrow_4->setPen(pen_user);

    line_3=  scene->addLine(400,240+20 , 400, 360-60+20);
    line_3->setPen(pen_user);

    btnUser = new QPushButton("用户") ;
    btnUser->setCheckable(true);
    btnUser->setChecked(!_gpio.on);
    QGraphicsProxyWidget * pWidgetUser=scene->addWidget(btnUser);
    pWidgetUser->setPos(300,360-60);
    pWidgetUser->setGeometry(QRect(360,360-60+20, 80, 40));
    pWidgetUser->setFlags(QGraphicsItem::ItemIsFocusable | QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemIsMovable); //通过QGraphicsProxyWidget指针设置其可选、可移动、可聚焦
    btnUser->setChecked(!_gpio.on);

    connect(btnUser, &QPushButton::clicked, [=] {
        //mHelper::ShowMessageBoxInfoX("用户");
        _gpio.on =0;
        updateChart();});

    QButtonGroup * group = new QButtonGroup;
    group->addButton(btnBus);
    group->addButton(btnUser);

    rs232com* rs232 = com_manager::instance()->get_com(com_name);
    if (rs232)
    {
        if (   rs232 ->myCom && rs232 ->myCom ->isOpen())
        {
            ui->pushButton_read->setEnabled(true);
            ui->pushButton_save->setEnabled(true);
        }
        else
        {
            ui->pushButton_read->setEnabled(false);
            ui->pushButton_save->setEnabled(false);
        }
    }
}

void Widget_GPIO_Output::updateChart( )
{
    QPen pen_enable (Qt::black , 3, Qt::SolidLine);
    QPen pen_disable(Qt::gray, 2, Qt::DashLine);


    QPen pen_pin(pen_enable);
    QPen pen_user(pen_disable);
    if ( !_gpio.on)
    {
        pen_pin = QPen(pen_disable);
        pen_user  = QPen(pen_enable);
    }

      remote_id->setText(QString::number(_gpio.remote_id));
      remote_bit->setText(QString::number(_gpio.remote_bit));

    ui->label_new_gpio->setText(_gpio.toString());

    user_default->setCurrentIndex( _gpio.level);
    btnFlip->setEnabled(_gpio.on);


    item_path->setPen(pen_pin);
    arrow_0->setPen(pen_pin);
    arrow_1->setPen(pen_pin);
    // arrow_2->setPen(pen_pin);
    arrow_2->setPen(pen_enable); //!!
    line_1->setPen(pen_pin);

   // user_path->setPen(pen_user);
    arrow_3->setPen(pen_user);
    line_3->setPen(pen_user);
arrow_4->setPen(pen_user);

    remote_id->setEnabled(_gpio.on);
    remote_bit->setEnabled(_gpio.on);
    remote_id->setText(QString::number(_gpio.remote_id));
    remote_bit->setText(QString::number(_gpio.remote_bit));

    btnFlip->setEnabled(_gpio.on);
    btnFlip->setChecked( _gpio.flip);
    btnBus->setChecked(_gpio.on);
    btnUser->setChecked(!_gpio.on);

    { GPIO* gpio = GpioSetting::gpio[com_name][gpio_id];
     ui->label_gpio->setText("寄存器值："+gpio->toString());
     }

    rs232com* rs232 = com_manager::instance()->get_com(com_name);
    if (rs232)
    {
        if (   rs232 ->myCom && rs232 ->myCom ->isOpen())
        {
            ui->pushButton_read->setEnabled(true);
            ui->pushButton_save->setEnabled(true);
        }
        else
        {
            ui->pushButton_read->setEnabled(false);
            ui->pushButton_save->setEnabled(false);
        }
    }
}

void Widget_GPIO_Output::on_pushButton_save_clicked()
{
    rs232com* rs232 = com_manager::instance()->get_com(com_name);
    if (rs232)
    {
        QByteArray save_str= rs232->set_gpio(gpio_id, _gpio.toString());
      //  ui->label_data->setText("写入："+save_str);

        GPIO * gpio = new GPIO;
        gpio->remote_id  = _gpio.remote_id ;
        gpio->remote_bit  = _gpio.remote_bit;
        gpio->flip  = _gpio.flip;
        gpio-> mode_input  = _gpio.mode_input;
        gpio-> level  = _gpio.level;
        gpio-> on  = _gpio.on;

        GpioSetting::gpio[com_name][gpio_id] = gpio;
    //    mHelper::ShowMessageBoxInfo("写入成功："+save_str);
        if (save_str.length() >0)
            mHelper::ShowMessageBoxInfo("写入成功");
        else
            mHelper::ShowMessageBoxInfo("写入失败");
    }
}


void Widget_GPIO_Output::on_pushButton_read_clicked()
{
    rs232com* rs232 = com_manager::instance()->get_com(com_name);
    if (rs232)
    {
        rs232->query_gpio(gpio_id);

        emit changePage();

    }
}
